# -*- coding:utf-8 -*-

import unittest
import json
#import urllib
import os
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains

class ido_test(unittest.TestCase):
    '''
    Demo版本测试验证
    需求：成员列表中至少有2人
    '''

    def setUp(self):
        '''
        准备工作
        '''
        #load test data
        with open('testData-h13.json', 'r') as fin:
            self.testData = json.load(fin)
        
        self.wait = {}
        self.wait["min"] = self.testData["waitTime"]["min"]
        self.wait["short"] = self.testData["waitTime"]["short"]
        self.wait["normal"] = self.testData["waitTime"]["normal"]
        self.wait["long"] = self.testData["waitTime"]["long"]
        self.wait["max"] = self.testData["waitTime"]["max"]
        
        self.by = { "id":By.ID, 
                    "name":By.NAME, 
                    "class":By.CLASS_NAME,
                    "tag":By.TAG_NAME, 
                    "link":By.LINK_TEXT,
                    "partial_link":By.PARTIAL_LINK_TEXT,
                    "xpath":By.XPATH,
                    "css":By.CSS_SELECTOR}

        #set test browser
        browserType = self.testData["browserType"]
        if (browserType == "chrome"):
            chromeDriver = self.testData['chromeDriver']
            os.environ["webdriver.chrome.driver"] = chromeDriver
            self.browser = webdriver.Chrome(chromeDriver)
        elif (browserType == "safari"):
            self.browser = webdriver.Safari()
        else:
            self.browser = webdriver.Firefox()
        time.sleep(self.wait["short"])

        #self.addCleanup(self.browser.quit)

    def testAppDemo(self):
        '''
        App Demo
        '''
        print("--- 登陆测试平台")
        self.stepOpenSite()
        self.stepLoginPlatform()
        #print("--- 创建新应用")
        #self.stepGotoAppManage()
        #self.stepAddNewApp()
        print("--- 创建测试实例")
        self.stepCreateTestInstance()
        print("--- 添加组件")
        self.stepAddComponent()
        print("--- 验证部署状态")
        self.stepCheckDeployStatus()
        print("--- 访问测试实例")
        self.stepAccessTestIntance()

    def stepOpenSite(self):
        print("\t.访问站点")
        data = self.testData['openSite']
        self.browser.get(data['urlSite'])
        time.sleep(self.wait["short"])
        self.assertIn(data['siteTitle'], self.browser.title)

    def stepLoginPlatform(self):
        data = self.testData["loginPlatform"]
        browser = self.browser
        by = self.by

        print("\t.输入登陆信息")
        elem = browser.find_element(by[data['txtUsername'][0]], data['txtUsername'][1])
        elem.send_keys(data['userName'])
        elem = browser.find_element(by[data['txtPassword'][0]], data['txtPassword'][1])
        elem.send_keys(data['userPassword'])
        
        print("\t.登陆")
        elem = browser.find_element(by[data['btnLogin'][0]], data['btnLogin'][1])
        elem.click()
        #self.browser.implicitly_wait(self.waitLong)
        time.sleep(self.wait["max"])
        self.assertEqual(data['urlAfterLogin'], browser.current_url)

    def stepGotoAppManage(self):
        data = self.testData["gotoAppManage"]
        browser = self.browser
        by = self.by
        
        print("\t.切换至［应用管理］")
        elem = browser.find_element(by[data["btnAppManage"][0]], data["btnAppManage"][1])
        elem.click()
        time.sleep(self.wait["max"])
        self.assertEqual(data["urlManageApp"], browser.current_url)
        
    def stepAddNewApp(self):
        data = self.testData["addNewApp"]
        browser = self.browser
        by = self.by

        print("\t.点击［添加新应用］")
        elem = browser.find_element(by[data["btnAddApp"][0]], data["btnAddApp"][1])
        elem.click()
        time.sleep(self.wait["max"])
        self.assertEqual(data["urlManageCreate"], browser.current_url)

        print("\t.添加应用图标")
        elem = browser.find_element(by[data["btnBrowse"][0]], data["btnBrowse"][1])
        elem.send_keys(data["appLogo"])
        elem = browser.find_element(by[data["btnUpload"][0]], data["btnUpload"][1])
        elem.click()
        time.sleep(self.wait["short"])
        #scroll page down
        browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        print("\t.设置应用基本信息")
        elem = browser.find_element(by[data["txtAppName"][0]], data["txtAppName"][1])
        elem.send_keys(data["appName"])
        elem = browser.find_element(by[data["txtProjectCode"][0]], data["txtProjectCode"][1])
        elem.send_keys(data["projectCode"])
        elem = browser.find_element(by[data["txtAppDescription"][0]], data["txtAppDescription"][1])
        elem.send_keys(data["appDescription"])
        
        print("\t.设置成员信息")
        #add 1 master
        elem = browser.find_element(by[data["listMember"][0]], data["listMember"][1])
        elem.click()
        member = data["memberBase"][1] + "[1]"
        elem = browser.find_element(by[data["memberBase"][0]], member)
        elem.click()
        elem = browser.find_element(by[data["listRole"][0]], data["listRole"][1])
        elem.click()
        elem = browser.find_element(by[data["linkMaster"][0]], data["linkMaster"][1])
        elem.click()
        #remove selected
        elem = browser.find_element(by[data["removeMember"][0]], data["removeMember"][1])
        elem.click()
        #add 1 member
        member = data["memberBase"][1] + "[2]"
        elem = browser.find_element(by[data["memberBase"][0]], member)
        elem.click()
        elem = browser.find_element(by[data["listRole"][0]], data["listRole"][1])
        elem.click()
        elem = browser.find_element(by[data["linkMember"][0]], data["linkMember"][1])
        elem.click()

        print("\t.下一步")
        elem = browser.find_element(by[data["btnNext"][0]], data["btnNext"][1])
        elem.click()
        time.sleep(self.wait["min"])
        elem = browser.find_element(by[data["sectionTitle"][0]], data["sectionTitle"][1])
        self.assertEqual(data["sectionTitle"][2], elem.text)

        print("\t.绑定开发测试节点")
        elem = browser.find_element(by[data["listNodeType"][0]],data["listNodeType"][1])
        elem.click()
        node = data["nodeTypeBase"][1] + "[1]"
        elem = browser.find_element(by[data["nodeTypeBase"][0]], node)
        elem.click()
        item = data["nodeItemBase"][1] + "1" + data["nodeItemBase"][2]
        elem = browser.find_element(by[data["nodeItemBase"][0]], item)
        elem.click()
        print("\t.绑定发布环境节点")
        elem = browser.find_element(by[data["listNodeType"][0]],data["listNodeType"][1])
        elem.click()
        node = data["nodeTypeBase"][1] + "[2]"
        elem = browser.find_element(by[data["nodeTypeBase"][0]], node)
        elem.click()
        item = data["nodeItemBase"][1] + "2" + data["nodeItemBase"][2]
        elem = browser.find_element(by[data["nodeItemBase"][0]], item)
        elem.click()
        time.sleep(self.wait["min"])

        print("\t.完成")
        elem = browser.find_element(by[data["btnDone"][0]], data["btnDone"][1])
        elem.click()
        time.sleep(self.wait["normal"])

    def stepCreateTestInstance(self):
        data = self.testData["createTestInstance"]
        browser = self.browser
        by = self.by

        print("\t.查找应用")
        baseSelector = data["app"][1]
        pos = baseSelector.find("]")
        appName = baseSelector[:pos] + data["appName"] + "]"
        elem = browser.find_element(by[data["app"][0]], appName)
        action = ActionChains(browser)
        action.move_to_element(elem)
        action.perform()
        time.sleep(self.wait["normal"])

        print("\t.点击［新建实例］")
        newInstance = appName + data["newInstance"][1]
        elem = browser.find_element(by[data["newInstance"][0]], newInstance)
        elem.click()
        time.sleep(self.wait["min"])

        print("\t.设置实例类别")
        elem = browser.find_element(by[data["listInstanceType"][0]], data["listInstanceType"][1])
        elem.click()
        elem = browser.find_element(by[data["instanceType"][0]], data["instanceType"][1])
        elem.click()

        print("\t.设置实例名称")
        elem = browser.find_element(by[data["filedInstanceName"][0]], data["filedInstanceName"][1])
        elem.send_keys(data["instanceName"])
        time.sleep(self.wait["normal"])

        elem = browser.find_element(by[data["btnOK"][0]], data["btnOK"][1])
        elem.click()

    def stepAddComponent(self):
        print("\t.添加redis组件")
        print("\t.添加前端组件")

    def stepCheckDeployStatus(self):
        pass

    def stepAccessTestIntance(self):
        pass

    def stepLogoutPlatform(self):
        '''
        退出测试平台
        '''
        print("--- 退出测试平台")
        print("\tPASS")

    def tearDown(self):
        '''
        收尾工作
        '''
        pass


def main():
    unittest.main()

if __name__ == '__main__':
    main()